package com.dangwen.proto.service;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class MqttPublisherService {
    private final MqttClient mqttClient;

    @Autowired
    public MqttPublisherService(MqttClient mqttClient) {
        this.mqttClient = mqttClient;
    }

    public void publishMessage(String topic, String content) throws MqttException {
        MqttMessage message = new MqttMessage(content.getBytes());
        message.setQos(1); // 0 - 至多一次，1 - 至少一次，2 - 只有一次
        System.out.println("发送的消息为：");
        mqttClient.publish(topic, message);
    }
}

